<template>
	<view class="dynamic-tabbar" :data-mode="currentMode">
		<view v-for="(item, index) in currentTabList" :key="index" @click="switchTab(item, index)" class="tab-item"
			:class="{ 
				active: currentIndex === index,
				'special-item': item.isLifeEntry || item.isMainEntry,
				'life-entry': item.isLifeEntry,
				'full-image': item.useFullImage
			}">
			<view class="tab-content">
				<!-- 如果使用完整图片 -->
				<image v-if="item.useFullImage" 
					:src="getImageUrl(currentIndex === index ? item.selectedIconPath : item.iconPath)" 
					class="tab-full-image"
					:class="{ 'life-full-image': item.isLifeEntry }"
					:mode="item.isLifeEntry ? 'scaleToFill' : 'aspectFill'">
				</image>
				<!-- 如果使用u-icon图标 -->
				<view v-else-if="item.useIcon && item.iconName" class="tab-icon-wrapper">
					<u-icon :name="item.iconName" 
						:size="32" 
						:color="currentIndex === index ? (currentMode === 'life' ? '#ff1e00' : '#000000') : '#909399'"
						:class="['tab-icon-uicon', { 'tab-icon-active': currentIndex === index }]">
					</u-icon>
					<text class="tab-text">{{ item.text }}</text>
				</view>
				<!-- 否则使用图片+文字 -->
				<view v-else class="tab-icon-wrapper">
					<image :src="getImageUrl(currentIndex === index ? item.selectedIconPath : item.iconPath)" class="tab-icon"></image>
					<text class="tab-text">{{ item.text }}</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import { inject } from 'vue'

export default {
	name: 'DynamicTabbar',
	components: {
		// u-icon 应该是全局注册的，但为了确保，可以在这里导入
	},
	setup() {
		const defaults = inject('$defaults')
		return {
			defaults
		}
	},
	data() {
		return {
			currentIndex: 0,
			currentMode: 'main', // 'main' 或 'life'
			// 主菜单
			mainTabList: [
				{
					pagePath: "pages/index/index",
					text: "首页",
					iconName: "home",
					useIcon: true, // 使用u-icon组件
					iconPath: "/static/tabbar/home.png",
					selectedIconPath: "/static/tabbar/home-active.png"
				},
				{
					pagePath: "pages/classification/index",
					text: "分类",
					iconName: "grid",
					useIcon: true, // 使用u-icon组件
					iconPath: "/static/tabbar/category.png",
					selectedIconPath: "/static/tabbar/category-active.png"
				},
				{
					pagePath: "pages/o2o/index",
					text: "生活",
					iconPath: "img/shou/shenghuo@2x.png",
					selectedIconPath: "img/shou/shenghuo@2x.png",
					isLifeEntry: true,
					useFullImage: true // 使用完整图片
				},
				{
					pagePath: "pages/cart/index",
					text: "购物车",
					iconName: "bag",
					useIcon: true, // 使用u-icon组件
					iconPath: "/static/tabbar/cart.png",
					selectedIconPath: "/static/tabbar/cart-active.png"
				},
				{
					pagePath: "pages/my/index",
					text: "我的",
					iconName: "account",
					useIcon: true, // 使用u-icon组件
					iconPath: "/static/tabbar/my.png",
					selectedIconPath: "/static/tabbar/my-active.png"
				}
			],
			// 生活菜单
			lifeTabList: [
				{
					pagePath: "pages/o2o/index",
					text: "首页",
					iconName: "home-fill",
					useIcon: true, // 使用u-icon组件
					iconPath: "/static/tabbar/home.png",
					selectedIconPath: "/static/tabbar/home-active.png"
				},
				{
					pagePath: "pages/index/index",
					text: "商城",
					iconPath: "img/o2o/shangcheng@2x.png",
					selectedIconPath: "img/o2o/shangcheng@2x.png",
					isMainEntry: true,
					useFullImage: true // 使用完整图片
				},
				{
					pagePath: "pages/my/index",
					text: "我的",
					iconName: "account",
					useIcon: true, // 使用u-icon组件
					iconPath: "/static/tabbar/my.png",
					selectedIconPath: "/static/tabbar/my-active.png"
				}
			]
		}
	},
	computed: {
		currentTabList() {
			return this.currentMode === 'main' ? this.mainTabList : this.lifeTabList;
		}
	},
	mounted() {
		this.initCurrentIndex();
	},
	onShow() {
		// 页面显示时重新初始化当前索引
		this.initCurrentIndex();
	},
	methods: {
		// 获取完整图片URL（拼接server_address前缀）
		getImageUrl(path) {
			if (!path) return ''
			// 如果路径以 http:// 或 https:// 开头，直接返回
			if (path.startsWith('http://') || path.startsWith('https://')) {
				return path
			}
			// 如果路径以 / 开头，说明是本地路径，直接返回
			if (path.startsWith('/')) {
				return path
			}
			// 否则拼接 server_address（图片服务器地址）
			const serverAddress = this.defaults?.defaults?.server_address || 'https://weixin.youpin91.com.cn/'
			// 确保 serverAddress 以 / 结尾，path 不以 / 开头
			const baseUrl = serverAddress.endsWith('/') ? serverAddress : serverAddress + '/'
			const imagePath = path.startsWith('/') ? path.substring(1) : path
			return baseUrl + imagePath
		},
		initCurrentIndex() {
			const pages = getCurrentPages();
			const currentPage = pages[pages.length - 1];
			const currentRoute = currentPage.route;

			console.log('当前页面路由:', currentRoute);

			// 判断是否是生活相关页面
			const isLifePage = currentRoute.includes('o2o/');

			if (isLifePage) {
				this.currentMode = 'life';
				console.log('切换到生活模式');
			} else {
				this.currentMode = 'main';
				console.log('切换到主模式');
			}

			// 在当前模式的tab列表中查找匹配的页面
			const index = this.currentTabList.findIndex(item => {
				const itemPath = item.pagePath.startsWith('/') ? item.pagePath.substring(1) : item.pagePath;
				return itemPath === currentRoute;
			});

			if (index !== -1) {
				this.currentIndex = index;
				console.log('找到匹配页面，索引:', index);
			} else {
				// 如果没找到匹配的，设置默认值
				this.currentIndex = 0;
				console.log('未找到匹配页面，使用默认索引 0');
			}
		},
		switchTab(item, index) {
			// 如果点击的是生活入口，切换到生活菜单
			if (item.isLifeEntry) {
				this.currentMode = 'life';
				this.currentIndex = 0; // 默认选中生活首页
				// 使用reLaunch确保页面栈清空，避免返回问题
				uni.reLaunch({
					url: `/${this.lifeTabList[0].pagePath}`,
					success: () => {
						console.log('成功切换到生活菜单');
					},
					fail: (err) => {
						console.error('切换到生活菜单失败:', err);
					}
				});
				return;
			}

			// 如果点击的是商城（返回主菜单入口）
			if (item.isMainEntry) {
				this.currentMode = 'main';
				this.currentIndex = 0; // 默认选中首页
				uni.reLaunch({
					url: `/${this.mainTabList[0].pagePath}`,
					success: () => {
						console.log('成功切换到主菜单');
					},
					fail: (err) => {
						console.error('切换到主菜单失败:', err);
					}
				});
				return;
			}

			// 更新当前选中索引
			this.currentIndex = index;

			// 普通页面跳转
			uni.navigateTo({
				url: `/${item.pagePath}`,
				fail: (err) => {
					console.error('页面跳转失败:', err);
				}
			});
		}
	}
}
</script>

<style scoped>
.dynamic-tabbar {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	height: 50px;
	background-color: #ffffff;
	display: flex;
	z-index: 1000;
	padding-bottom: env(safe-area-inset-bottom);
}

.tab-item {
	flex: 1;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: flex-end;
	padding: 4px 0;
	position: relative;
}

.tab-content {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
}

.tab-icon-wrapper {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
}

/* 特殊菜单项样式 */
.tab-item.special-item {
	justify-content: center;
	z-index: 10;
	height: 60px;
}

.tab-item.special-item .tab-content {
	border-radius: 50%;
	width: 60px;
	height: 60px;
	position: relative;
	top: -7px;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
}

/* 商城入口（isMainEntry）的样式 */
.tab-item.special-item:not(.life-entry) .tab-content {
	background: linear-gradient(135deg, #FF6B6B 0%, #FF5252 100%);
	box-shadow: 
		0 8px 20px rgba(255, 107, 107, 0.4),
		0 4px 8px rgba(0, 0, 0, 0.1);
	border: 4px solid #ffffff;
}

.tab-item.special-item:not(.life-entry).active .tab-content {
	background: linear-gradient(135deg, #FF5252 0%, #E53935 100%);
	transform: scale(1.08);
	box-shadow: 
		0 10px 25px rgba(255, 82, 82, 0.5),
		0 6px 12px rgba(0, 0, 0, 0.15);
}

.tab-item.special-item:not(.life-entry) .tab-icon {
	width: 30px;
	height: 30px;
	margin-bottom: 1px;
	filter: brightness(0) invert(1);
	z-index: 2;
	position: relative;
}

.tab-item.special-item:not(.life-entry) .tab-text {
	color: #ffffff;
	font-size: 8px;
	font-weight: 600;
	text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
	z-index: 2;
	position: relative;
}

/* 普通菜单项样式 */
/* 主模式下选中状态为橙色 */
.dynamic-tabbar:not([data-mode="life"]) .tab-item:not(.special-item).active .tab-text {
	color: #FF8033;
}

/* 生活模式下选中状态为红色 */
.dynamic-tabbar[data-mode="life"] .tab-item:not(.special-item).active .tab-text {
	color: #ff3333;
}

.tab-icon {
	width: 24px;
	height: 24px;
	margin-bottom: 2px;
}

.tab-icon-uicon {
	margin-bottom: 2px;
}

.tab-icon-uicon.tab-icon-active {
	border: 1px solid #000000;
	border-radius: 4px;
	padding: 2px;
}

.tab-text {
	font-size: 12px;
	color: #999999;
	line-height: 1;
}

/* 完整图片样式 */
.tab-item.full-image .tab-content {
	width: 100%;
	height: 100%;
	display: flex;
	align-items: center;
	justify-content: center;
}

.tab-full-image {
	width: 100%;
	height: 100%;
	max-width: 100%;
	max-height: 100%;
}

/* 生活入口使用完整图片时的样式 */
.tab-item.life-entry.full-image .tab-content {
	width: 160rpx;
	height: 160rpx;
	min-width: 160rpx;
	min-height: 160rpx;
	max-width: 160rpx;
	max-height: 160rpx;
	border-radius: 50%;
	overflow: hidden;
	position: relative;
	top: -30rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.tab-item.life-entry.full-image .tab-full-image.life-full-image {
	width: 160rpx !important;
	height: 160rpx !important;
	min-width: 160rpx !important;
	min-height: 160rpx !important;
	max-width: 160rpx !important;
	max-height: 160rpx !important;
	border-radius: 50% !important;
	object-fit: cover;
	display: block;
}

/* 商城入口（isMainEntry）使用完整图片时的样式 - 参考生活入口 */
.tab-item.special-item.full-image .tab-content {
	width: 130rpx;
	height: 130rpx;
	min-width: 130rpx;
	min-height: 130rpx;
	max-width: 130rpx;
	max-height: 130rpx;
	border-radius: 50%;
	overflow: visible;
	position: relative;
	top: -23rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	background: transparent;
	box-shadow: none;
	border: none;
}

.tab-item.special-item.full-image .tab-full-image {
	width: 130rpx !important;
	height: 130rpx !important;
	min-width: 130rpx !important;
	min-height: 130rpx !important;
	max-width: 130rpx !important;
	max-height: 130rpx !important;
	border-radius: 50% !important;
	object-fit: cover;
	display: block;
}

/* 动画效果 */
.tab-item.special-item .tab-content {
	transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.tab-item.special-item .tab-content::before {
	transition: opacity 0.3s ease;
}

.tab-item.special-item:active .tab-content {
	transform: scale(0.92);
}

/* 悬停效果（适用于支持的设备） */
@media (hover: hover) {
	.tab-item.special-item:hover .tab-content {
		transform: scale(1.02);
	}
	
	.tab-item.special-item.active:hover .tab-content {
		transform: scale(1.1);
	}
}
</style>